<?php

namespace app\admin\controller\express;

use app\admin\library\Export;
use app\common\controller\Backend;
use app\common\model\Category;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 批次管理
 *
 * @icon fa fa-circle-o
 */
class Batch extends Backend
{

    /**
     * Batch模型对象
     * @var \app\admin\model\express\Batch
     */
    protected $model = null;
    protected $selectpageFields = "id,batch_no,createtime_text";
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\express\Batch;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

     /*
      * 改变批次状态
      * */
    public function setStatus(){
        $params = $this->request->post('row/a');
        Db::startTrans();
        try {
            $this->model->where('id', 'in', $params['ids'])->setField('status', $params['status']);
            $packageList = model('app\admin\model\express\Package')->where('batch_id','in',$params['ids'])->select();
            $packageData = $packageTrackData = [];
            foreach ($packageList as $package){
                $packageData[] = [
                    'id' => $package['id'],
                    'status' => $params['status']
                ];
                $track = model('app\admin\model\express\PackageTrack')->where([
                    'package_id' => $package['id'],
                    'status' => $params['status']
                ])->find();
                if($track){
                    $packageTrackData[] = [
                        'id' => $track['id'],
                        'admin_id' => $this->auth->id,
                        'memo' => $params['memo'],
                        'createtime' => time()
                    ];
                }else{
                    $packageTrackData[] = [
                        'package_id' => $package['id'],
                        'status' => $params['status'],
                        'memo' => $params['memo'],
                        'admin_id' => $this->auth->id,
                    ];
                }
            }
            model('app\admin\model\express\Package')->saveAll($packageData);
            model('app\admin\model\express\PackageTrack')->saveAll($packageTrackData);
            Db::commit();
        }  catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success();
    }

    /*
     * 下载身份证
     * */
    public function download($ids = null){
        $packageList = model('app\admin\model\express\Package')->where('batch_id','in',$ids)->select();
        $tmpDir = ROOT_PATH.'public/uploads/zip/';

        if (!file_exists($tmpDir)) {
            //创建文件夹
            mkdir($tmpDir, 0777, true);
        }
        $zipName = date('His') . mt_rand(1000, 9999) . '.zip'; // 压缩包文件名
        $zipNameUrl = $tmpDir . $zipName; // 文件路径
        $zip = new \ZipArchive();

        if ($zip->open($zipNameUrl, \ZipArchive::OVERWRITE) !== true) {
            //OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
            if ($zip->open($zipNameUrl, \ZipArchive::CREATE) !== true) {
                // 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
                $this->error( '下载失败，文件夹不存在');
            }
        }


        foreach ($packageList as $row){

            $row['address'] = model('app\admin\model\express\OrderAddress')
                ->where(['order_id' => $row['order_id']])
                ->find();
            //正面
            $image = $row['address']['idcard_merge'];
            if($image){
                $image = ROOT_PATH.'public'.$image;
                $image_end = strrpos($image,'.');
                $image_start = strrpos($image,'/');
                $new_front_file = str_replace(substr($image,$image_start ,$image_end - $image_start),'/'.'_'.$row['address']['idcard'],$image);
                copy($image, $new_front_file);
                //反面

                //抓取图片内容
                $frontFileContent = file_get_contents($new_front_file);
                //添加图片
                $zip->addFromString(basename($new_front_file), $frontFileContent);
            }

        }
        // 关闭
        $zip->close();

        //没有文件
        if (!file_exists($zipNameUrl)) {
            $this->error('下载失败，文件不存在或无法下载');
        }

        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . $zipName); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: ' . filesize($zipNameUrl)); //告诉浏览器，文件大小

        // 下面2步必须要
        ob_clean();
        flush();

        @readfile($zipNameUrl);
        unlink($zipNameUrl); // 删除文件
        exit;
    }



    /*
    * 下载身份证
    * */
    public function download1($ids = null){
        $packageList = model('app\admin\model\express\Package')->where('batch_id','in',$ids)->select();
        $tmpDir = ROOT_PATH.'public/uploads/zip/';

        if (!file_exists($tmpDir)) {
            //创建文件夹
            mkdir($tmpDir, 0777, true);
        }
        $zipName = date('His') . mt_rand(1000, 9999) . '.zip'; // 压缩包文件名
        $zipNameUrl = $tmpDir . $zipName; // 文件路径
        $zip = new \ZipArchive();

        if ($zip->open($zipNameUrl, \ZipArchive::OVERWRITE) !== true) {
            //OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
            if ($zip->open($zipNameUrl, \ZipArchive::CREATE) !== true) {
                // 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
                $this->error( '下载失败，文件夹不存在');
            }
        }


        foreach ($packageList as $row){

            $row['address'] = model('app\admin\model\express\OrderAddress')
                ->where(['order_id' => $row['order_id']])
                ->find();
            //正面
            $image = $row['address']['idcard_merge'];
            if($image){
                $image = ROOT_PATH.'public'.$image;
                $image_end = strrpos($image,'.');
                $image_start = strrpos($image,'/');
                $new_front_file = str_replace(substr($image,$image_start ,$image_end - $image_start),'/'.'_'.$row['address']['idcard'],$image);
                copy($image, $new_front_file);
                //反面

                //抓取图片内容
                $frontFileContent = file_get_contents($new_front_file);
                //添加图片
                $zip->addFromString(basename($new_front_file), $frontFileContent);
            }

        }
        // 关闭
        $zip->close();

        //没有文件
        if (!file_exists($zipNameUrl)) {
            $this->error('下载失败，文件不存在或无法下载');
        }

        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename=' . $zipName); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: ' . filesize($zipNameUrl)); //告诉浏览器，文件大小

        // 下面2步必须要
        ob_clean();
        flush();

        @readfile($zipNameUrl);
        unlink($zipNameUrl); // 删除文件
        exit;
    }


    /*
     * 扫描包裹加入批次
     * */
    public function scanning($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $express_no = $this->request->post('express_no');
            $package = \app\admin\model\express\Package::get([
                'express_no' => $express_no
            ],['address']);
            if(!$package){
                $this->error('该包裹不存在');
            }
            $packageOnly = \app\admin\model\express\Package::with(['address'])
                ->where('batch_id',$ids)
                ->where(function ($query) use($package){
                    $query->where('address.name' , $package['address']['name']);
                        //->whereOr('address.idcard',$package['address']['idcard']);
                })
                ->count();
            if($packageOnly>=2){
                $this->error('该收件人已存在(收货人姓名重复)不能重复2次以上');
            }

            $packageOnly = \app\admin\model\express\Package::with(['address'])
                ->where('batch_id',$ids)
                ->where(function ($query) use($package){
                    $query
                        ->where('address.mobile',$package['address']['mobile']);
                    //->whereOr('address.idcard',$package['address']['idcard']);
                })->count();

            if($packageOnly>=2){
                $this->error('该收件人已存在(手机号重复)不能重复2次以上');
            }

            $packageOnly = \app\admin\model\express\Package::with(['address'])
                ->where('batch_id',$ids)
                ->where(function ($query) use($package){
                    $query
                    ->where('address.province',$package['address']['province'])
                    ->where('address.city',$package['address']['city'])
                    ->where('address.area',$package['address']['area'])
                    ->where('address.address',$package['address']['address']);
                })->count();

            if($packageOnly>=2){
                $this->error('该收件人已存在(收货地址)不能重复2次以上');
            }

           /* if($packageOnly){
                if($package['address']['name'] == $packageOnly['address']['name']){
                    $this->error('该收件人已存在(收货人姓名重复)');
                }
                if($package['address']['mobile'] == $packageOnly['address']['mobile']){
                    $this->error('该收件人已存在(手机号重复)');
                }
                if($package['address']['idcard'] == $packageOnly['address']['idcard']){
                    $this->error('该收件人已存在(身份证号重复)');
                }
            }*/

            $params = [
                'batch_id' => $ids,
                'status' => $row['status']
            ];
            $result = false;
            $result = $package->allowField(true)->save($params);
            $number = \app\admin\model\express\Package::where('batch_id',$ids)->count();
            $row->allowField(true)->save(['number'=>$number]);
            if($result !== false){

                $this->success();
            }else{
                $this->error();
            }
        }
        return $this->view->fetch();
    }

    /*
     * 导出批次包裹
     * */
    public function export($ids = null)
    {
        $export = new Export();
        $list = model('app\admin\model\express\Package')
            ->with(['expressorder','user','goods'])
            ->where('batch_id','in',$ids)->select();

        $expCellName = [
            'index' => '计数',
            'express_no' => '分运单号',
            'address_name' => '微信昵称',
            'delivery_name' => '发件人姓名',

            'address_name2' => '收件人姓',
            'address_mobile' => '收件人联系方式',
            'address_idcard' => '收发件人证件号',
            'address_province' => '省',
            'address_city' => '市',
            'address_area' => '区',
            'address_address' => '收件地址',
            'address_zip_code' => '邮编',

            'country' => '发件人国别',
            'delivery_city' => '发件人城市',
            'production_country' => '产销国',
//            'idcard_id' => '收发件人证件',
//            'address_idcard' => '收发件人证件号',
            'delivery_name2' => '英文发件人',
            'delivery_city2' => '英文发件人城市',
            'stop_city' => '英文经停城市',
            'delivery_address' => '英文发件人地址',

            'delivery_address2' => '发件人地址',
            'delivery_mobile' => '发件人电话',
            'address_city2' => '收件人城市',
            'production_city' => '产销城市',
        ];

        $packCellName = [
            'goods_number_one' => '件数',
            'package_weight' => '包裹毛重',
            'delivery_price' => '运费',
        ];

        $goodsCellName = [
            'goods_name' => '商品名称',
            'goods_name2' => '英文商品名',
            'tax_no' => '行邮税号',
            'goods_brand' => '物品品牌',
            'goods_sku' => '商品规格型号',
            'number_unit' => '计量',
            'goods_number' => '内件数量',
            'goods_price' => '单件物品申报',
            'goods_weight' => '商品净重',
        ];

        $newList = [];
        $index = 1;
        $max_goods_num = 0;

        foreach ($list as $key => $order) {
            $data = [];
            $address = model('app\admin\model\express\OrderAddress')
                ->where(['order_id' => $order['order_id']])
                ->find();
            $delivery_address = Db::name('express_delivery_address')->where('id',$order['delivery_address_id'])->find();
            $num = 0;
            $user = model('app\admin\model\user')
                ->where(['id' => $order['user_id']])
                ->find();
            if(empty($user)){
                $nickname="";
            }else{
                $nickname = $user['nickname'];
            }

            $data['package']=[
                'index' => $index,
                'express_no' => $order['express_no'],
                'address_name' => $nickname,
                'delivery_name' => $delivery_address['name'],
                'address_name2' => $address['name'],
                'address_mobile' => $address['mobile'],
                'address_province' => $address['province'],
                'address_city' => $address['city'],
                'address_area' => $address['area'],
             //   'address_address' => $address['province'].$address['city'].$address['area'].$address['address'],
                'address_address' => $address['address'],
                'address_zip_code' => $address['zip_code'],
                'country' => 'BE',
                'delivery_city' => '布鲁塞尔',
                'production_country' => '301',
                'idcard_id' => '1',
                'address_idcard' => $address['idcard'],
                'delivery_name2' => $delivery_address['name'],
                'delivery_city2' => 'bruxelles',
                'stop_city' => '',
                'delivery_address' => $delivery_address['address'],
                'delivery_address2' => '布鲁塞尔',
                'delivery_mobile' => $delivery_address['mobile'],
                'address_city2' => $address['city'],
                'production_city' => 'bruxelles',
            ];

            foreach ($order['goods'] as $goods){
                $tax_no = Category::where('id',$goods['category_id'])->value('tax_no');
                $data['goods'][] = [
                        'goods_name' => $goods['description'],
                        'tax_no' => $tax_no ? $tax_no : '',
                        'goods_brand' => $goods['brand'],
                        'goods_sku' => $goods['name'].'|'.$goods['brand'].'|'.$goods['weight'].$goods['unit'].'|'.$goods['sku'],
                        'number_unit' => $goods['number_unit'],
                        'goods_number' => $goods['number'],
                        'goods_price' => $goods['price'],
                        'goods_number_one' => 1,
                        'package_weight' => $order['weight'],
                        'goods_weight' => bcdiv($goods['weight'],1000,2),
                        'delivery_price' => $order['delivery_price'],
                        'delivery_name' => $delivery_address['name'],
                        'address_name2' => $address['name'],
                        'address_mobile' => $address['mobile'],
                        'address_province' => $address['province'],
                        'address_city' => $address['city'],
                        'address_area' => $address['area'],
                        'address_address' => $address['province'].$address['city'].$address['area'].$address['address'],
                        'address_zip_code' => $address['zip_code'],
                        'goods_name2' => $goods['brand'],
                        'production_city' => 'bruxelles',
                    ];
            }

            $data['package_end'] = [
                "goods_number_one" => count($data['goods']),
                'package_weight' => $order['weight'],
                'delivery_price' => $order['delivery_price'],
            ];
            if($data['package_end']["goods_number_one"]>$max_goods_num){
                $max_goods_num = $data['package_end']["goods_number_one"];
            }
            $index++;

            $newList[]=$data;
        }



//        p($newList);die;

        $export->exportExcel(date('Y.m.d').'订单' , $expCellName,$packCellName,$goodsCellName,$max_goods_num, $newList);
    }

    /*
    * 导出批次包裹
    * */
    public function export1($ids = null)
    {
        $export = new Export();
        $list = model('app\admin\model\express\Package')
            ->with(['expressorder','user','goods'])
            ->where('batch_id','in',$ids)->select();

        $expCellName = [
            'index' => '计数',
            'express_no' => '分运单号',
            'address_name' => '微信昵称',
            'delivery_name' => '发件人姓名',

            'address_name2' => '收件人姓',
            'address_mobile' => '收件人联系方式',
            'address_province' => '省',
            'address_city' => '市',
            'address_area' => '区',
            'address_address' => '收件地址',
            'address_zip_code' => '邮编',

            'country' => '发件人国别',
            'delivery_city' => '发件人城市',
            'production_country' => '产销国',
            'idcard_id' => '收发件人证件',
            'address_idcard' => '收发件人证件号',
            'delivery_name2' => '英文发件人',
            'delivery_city2' => '英文发件人城市',
            'stop_city' => '英文经停城市',
            'delivery_address' => '英文发件人地址',

            'delivery_address2' => '发件人地址',
            'delivery_mobile' => '发件人电话',
            'address_city2' => '收件人城市',
            'goods_name2' => '英文商品名',
            'production_city' => '产销城市',
        ];

        $packCellName = [
            'goods_number_one' => '件数',
            'package_weight' => '包裹毛重',
            'delivery_price' => '运费',
        ];

        $goodsCellName = [
            'goods_name' => '商品名称',
            'tax_no' => '行邮税号',
            'goods_brand' => '物品品牌',
            'goods_sku' => '商品规格型号',
            'number_unit' => '计量',
            'goods_number' => '内件数量',
            'goods_price' => '单件物品申报',
            'goods_weight' => '商品净重',
        ];

        $newList = [];
        $index = 1;
        $max_goods_num = 0;
        foreach ($list as $key => $order) {
            $address = model('app\admin\model\express\OrderAddress')
                ->where(['order_id' => $order['order_id']])
                ->find();
            $delivery_address = Db::name('express_delivery_address')->where('id',$order['delivery_address_id'])->find();
            $num = 0;
            $user = model('app\admin\model\user')
                ->where(['id' => $order['user_id']])
                ->find();
            if(empty($user)){
                $nickname="";
            }else{
                $nickname = $user['nickname'];
            }

            foreach ($order['goods'] as $goods){
                $tax_no = Category::where('id',$goods['category_id'])->value('tax_no');
                if($num === 0){
                    $data = [
                        'index' => $index,
                        'express_no' => $order['express_no'],
                        'address_name' => $nickname,
                        'goods_name' => $goods['description'],
                        'tax_no' => $tax_no ? $tax_no : '',
                        'goods_brand' => $goods['brand'],
                        'goods_sku' => $goods['name'].'|'.$goods['brand'].'|'.$goods['weight'].$goods['unit'].'|'.$goods['sku'],
                        'number_unit' => $goods['number_unit'],
                        'goods_number' => $goods['number'],
                        'goods_price' => $goods['price'],
                        'goods_number_one' => 1,
                        'package_weight' => $order['weight'],
                        'goods_weight' => bcdiv($goods['weight'],1000,2),
                        'delivery_price' => $order['delivery_price'],
                        'delivery_name' => $delivery_address['name'],
                        'address_name2' => $address['name'],
                        'address_mobile' => $address['mobile'],
                        'address_province' => $address['province'],
                        'address_city' => $address['city'],
                        'address_area' => $address['area'],
                        'address_address' => $address['province'].$address['city'].$address['area'].$address['address'],
                        'address_zip_code' => $address['zip_code'],
                        'country' => 'BE',
                        'delivery_city' => '布鲁塞尔',
                        'production_country' => '301',
                        'idcard_id' => '1',
                        'address_idcard' => $address['idcard'],
                        'delivery_name2' => $delivery_address['name'],
                        'delivery_city2' => 'bruxelles',
                        'stop_city' => '',
                        'delivery_address' => $delivery_address['address'],
                        'delivery_address2' => '布鲁塞尔',
                        'delivery_mobile' => $delivery_address['mobile'],
                        'address_city2' => $address['city'],
                        'goods_name2' => $goods['brand'],
                        'production_city' => 'bruxelles',
                    ];
                }
                else{

                    $data = [
                        'index' => '',
                        'express_no' => $order['express_no'],
                        'address_name' => $nickname,
                        'goods_name' => $goods['description'],
                        'tax_no' => $tax_no ? $tax_no : '',
                        'goods_brand' => $goods['brand'],
                        'goods_sku' => $goods['name'].'|'.$goods['brand'].'|'.$goods['weight'].$goods['unit'].'|'.$goods['sku'],
                        'number_unit' => $goods['number_unit'],
                        'goods_number' => $goods['number'],
                        'goods_price' => $goods['price'],
                        'goods_number_one' => 1,
                        'package_weight' => $order['weight'],
                        'goods_weight' => bcdiv($goods['weight'],1000,2),
                        'delivery_price' => $order['delivery_price'],
                        'delivery_name' => $delivery_address['name'],
                        'address_name2' => $address['name'],
                        'address_mobile' => $address['mobile'],
                        'address_province' => $address['province'],
                        'address_city' => $address['city'],
                        'address_area' => $address['area'],
                        'address_address' => $address['province'].$address['city'].$address['area'].$address['address'],
                        'address_zip_code' => $address['zip_code'],
                        'country' => 'BE',
                        'delivery_city' => '布鲁塞尔',
                        'production_country' => '301',
                        'idcard_id' => '1',
                        'address_idcard' => $address['idcard'],
                        'delivery_name2' => $delivery_address['name'],
                        'delivery_city2' => 'bruxelles',
                        'stop_city' => '',
                        'delivery_address' => $delivery_address['address'],
                        'delivery_address2' => '布鲁塞尔',
                        'delivery_mobile' => $delivery_address['mobile'],
                        'address_city2' => $address['city'],
                        'goods_name2' => $goods['brand'],
                        'production_city' => 'bruxelles',
                    ];
                }
                $num ++;
                $newList[] = $data;
            }

            $index++;
        }



        $export->exportExcel(date('Y.m.d').'订单' , $expCellName, $newList);
    }


    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit)->each(function($item,$key){
                    $item->number = Db::name('express_package')->where('batch_id',$item->id)->count();
                    //$item->number = 100;
                    return $item;
                });

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
}
